﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using MediumApi.Result;

namespace MediumApi.Tools
{
    public class ApiAuthorityAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            try
            {
                var controller = context.RouteData.Values["controller"].ToString();
                var action = context.RouteData.Values["action"].ToString();
                var httpcontext = context.HttpContext;

                //取得header中的auth的token信息
                string token = httpcontext.Request.Headers["Token"];
                if (string.IsNullOrEmpty(token))
                {
                    context.Result = new ContentResult
                    {
                        Content = JsonConvert.SerializeObject(new TokenOperateResult() { success = true, errorCode = 401, msg = "请传入Token" }), //这里是把异常抛出。也可以不抛出。
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "text/html;charset=utf-8"
                    };
                    return;
                }

                //解密
                var json = TokenHelpers.DecodeToObject(token);
                if (json == null)
                {
                    context.Result = new ContentResult
                    {
                        Content = JsonConvert.SerializeObject(new TokenOperateResult() { success = true, errorCode = 401, msg = "Token解析失败" }), //这里是把异常抛出。也可以不抛出。
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "text/html;charset=utf-8"
                    };
                    return;
                }
                else if (DateTime.Now > Convert.ToDateTime(json.Ticks))
                {
                    context.Result = new ContentResult
                    {
                        Content = JsonConvert.SerializeObject(new TokenOperateResult() { success = true, errorCode = 401, msg = "Token失效" }), //这里是把异常抛出。也可以不抛出。
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "text/html;charset=utf-8"
                    };
                    return;
                }

            }
            catch (Exception e)
            {
                context.Result = new ContentResult
                {
                    Content = JsonConvert.SerializeObject(new OperateResult() { Success = true, ErrorCode = 401, Msg = "异常：" + e.Message }), //这里是把异常抛出。也可以不抛出。
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
                return;
            }
        }
    }
}
